package com.nice.common;

import org.springframework.core.io.ClassPathResource;

import java.io.*;
import java.util.ArrayList;
import java.util.List;

//将对象存储到文本
public class ReadObject {

    /**
     * 读取文件里的对象信息
     * @param objName 文件名
     * @return
     */
    public static Object readObject(String objName) {
        ObjectInputStream objectInputStream;
        Object obj =null;
        try {
            File file = new File(objName + ".txt");
            if (!file.exists()) {
                file.createNewFile();// 能创建多级目录
            }
            objectInputStream = new ObjectInputStream(new FileInputStream(file));
            obj =  objectInputStream.readObject();
            objectInputStream.close();
            System.out.println("反序列化结果为："+obj);
        } catch (Exception e) {

        }
        return obj;
    }

    /***
     * 对象写进文本
     * @param obj 对象
     * @param fileName 文件名
     */
    public static void writeObjcect(Object obj,String fileName) {
        try {
            ObjectOutputStream ooStream = new ObjectOutputStream(new FileOutputStream(fileName+".txt"));
            ooStream.writeObject(obj);
            ooStream.close();
            System.out.println("对象序列化成功");
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * 读取文本内容
     * @param filePathAndname
     * @return
     * @throws IOException
     */
    private static List<String> readFile(String filePathAndname) throws IOException {
        List<String> list = new ArrayList<String>();
        ClassPathResource classPathResource = new ClassPathResource(filePathAndname);
        InputStream inputStream = classPathResource.getInputStream();
        BufferedReader br = new BufferedReader(new InputStreamReader(inputStream));
        String line = null;
        while ((line = br.readLine()) != null) {
            list.add(line);
        }
        br.close();
        return list;

    }


//    public static void main(String[] args) {
//        PriceSchema priceSchema = new PriceSchema();
//        priceSchema.setIndexName("asdfafas");
//        priceSchema.setAsk("sadfa");
//        writeObjcect(priceSchema,"priceSchema");
//        System.out.println("结果："+readObject("priceSchema"));
//
//        Map<String, PriceSchema> map = new HashMap<>();
//        map.put(priceSchema.getIndexName(), priceSchema);
//        writeObjcect(map,"priceMap");
//        System.out.println("结果："+readObject("priceMap"));
//
//    }

//    public static void main(String[] args) throws IOException {
//        System.out.println(readFile("RealTime.txt"));
//    }
}
